
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { ref, reactive, watch, onMounted } from "vue";
import {
  BuildCollectionStrategyBaseData, BuildCollectionStrategy, CollectionStrategyList, CollectionStrategyDetail, IsLooked
} from "@/api/stu/bankBigData";
import { useRoute } from "vue-router";
import { cloneDeep } from "@pureadmin/utils";
export function useRiskStrategic() {
  const route = useRoute();
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const CreditVisible = ref<boolean>(false);
  const detailVisible = ref<boolean>(false);
  const regex = /[\u4e00-\u9fa5]{6,20}/;// 校验2-4个字中文
  const showTitle = ref()
  const showType = ref()
  const showData = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const formData = reactive({
    modelName: '',
    customerType: '',
    //评级集合
  })
  const companyList = reactive([{
    evaluationGrade: '',
    collectionType: '',
    collectionMethod: '',
    minOverdueAmount: '',
    maxOverdueAmount: '',
    collectionTime: '',
    collectionByList: [],
  }])

  const retailList = reactive([{
    evaluationGrade: '',
    collectionType: '',
    collectionMethod: '',
    minOverdueAmount: '',
    maxOverdueAmount: '',
    collectionTime: '',
    collectionByList: [],
  }])
  const companyGradeList = ref([]) //公司客户等级
  const retailGradeList = ref([]) //零售客户等级
  const collectionTimeList = ref([]) //催收时间
  const collectionTypeList = ref([]) //催收类型
  //根据类型联动
  const precollectionList = ref([])
  const territorialCollectionList = ref([])
  const outsourcedCollectionList = ref([])
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    },
    {
      label: "策略名称",
      prop: "policyName",
      minWidth: 200
    },
    {
      label: "客户类型",
      prop: "customerType",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }
  // 确定新建
  async function SubmitVisible() {
    if (regex.test(formData.modelName) === false) {
      ElMessage.warning('策略名称应输入6-20个汉字')
      return
    }
    let hasErr = false
    companyList.forEach(item => {
      console.log(item.minOverdueAmount);
      console.log(item.maxOverdueAmount);


      if (Number(item.minOverdueAmount) > Number(item.maxOverdueAmount)) {
        ElMessage.warning('最小逾期金额不能大于最大逾期金额')
        hasErr = true
        return
      }
    })
    retailList.forEach(item => {
      if (Number(item.minOverdueAmount) > Number(item.maxOverdueAmount)) {
        ElMessage.warning('最小逾期金额不能大于最大逾期金额')
        hasErr = true
        return
      }
    })
    if (hasErr) {
      return
    }
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      customerType: 'CompanyCustomers',
      policyName: formData.modelName,
      gradeInfos: [],
    }
    if (formData.customerType === 'CompanyCustomers') {
      const gradeInfos = []
      companyList.forEach(item => {
        console.log(item.collectionMethod);
        console.log(item.collectionTime);

        gradeInfos.push({
          collectionDifficulty: item.evaluationGrade,
          collectionType: item.collectionType,
          collectionMethod: item.collectionMethod ? item.collectionMethod.join(',') : '',
          minOverdueAmount: item.minOverdueAmount,
          maxOverdueAmount: item.maxOverdueAmount,
          collectionTime: item.collectionTime ? item.collectionTime.join(',') : '',
        })
      })
      data.gradeInfos = gradeInfos
      data.studentAnswer = JSON.stringify(data)
    }
    else {
      const gradeInfos = [];
      data.customerType = 'RetailCustomers'
      retailList.forEach(item => {
        gradeInfos.push({
          collectionDifficulty: item.evaluationGrade,
          collectionType: item.collectionType,
          collectionMethod: item.collectionMethod ? item.collectionMethod.join(',') : '',
          minOverdueAmount: item.minOverdueAmount,
          maxOverdueAmount: item.maxOverdueAmount,
          collectionTime: item.collectionTime ? item.collectionTime.join(',') : '',
        })
      })
      data.gradeInfos = gradeInfos;
      data.studentAnswer = JSON.stringify(data);
    }
    BtnLoading.value = true;
    OUTBtnLoding()
    const res = await BuildCollectionStrategy(data);
    if (res.success) {
      ElMessage.success(res.msg)
      CloseVisible()
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  }
  //置空表单
  function CloseVisible() {
    CreditVisible.value = false;
    companyList.splice(0, companyList.length);
    companyList.push({
      evaluationGrade: '',
      collectionType: '',
      collectionMethod: '',
      minOverdueAmount: '',
      maxOverdueAmount: '',
      collectionTime: '',
      collectionByList: [],
    })
    retailList.splice(0, retailList.length);
    retailList.push({
      evaluationGrade: '',
      collectionType: '',
      collectionMethod: '',
      minOverdueAmount: '',
      maxOverdueAmount: '',
      collectionTime: '',
      collectionByList: [],
    })
    formData.customerType = ''
    formData.modelName = ''
  }

  function handleSizeChange() {
    getList()
  }


  function handleCurrentChange() {
    getList()
  }


  async function getList() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
    }
    const res = await CollectionStrategyList(data);
    if (res.success) {
      res.data?.items.forEach(item => {
        item.createTime = item.createTime.substring(0, 10)
      })
      pagination.total = res.data.totalCount;
      dataList.value = res.data.items;
      loading.value = false;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        loading.value = false;
      }, 1500)
    }
  }


  function updateTypeSelect(index, select) {
    companyList[index].collectionMethod = ''
    if (select == '前期催收') {
      console.log(precollectionList.value);
      companyList[index].collectionByList = cloneDeep(precollectionList.value)
      console.log(companyList[index].collectionByList);
    }
    if (select == '属地催收') {
      companyList[index].collectionByList = cloneDeep(territorialCollectionList.value)
    }
    if (select == '委外催收') {
      companyList[index].collectionByList = cloneDeep(outsourcedCollectionList.value)
    }
  }

  function updateTypeSelect1(index, select) {
    retailList[index].collectionMethod = ''
    if (select == '前期催收') {
      retailList[index].collectionByList = cloneDeep(precollectionList.value)
    }
    if (select == '属地催收') {
      retailList[index].collectionByList = cloneDeep(territorialCollectionList.value)
    }
    if (select == '委外催收') {
      retailList[index].collectionByList = cloneDeep(outsourcedCollectionList.value)
    }
  }


  //处理新建模型数据
  async function handleCreatedModelData() {
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
    }
    let res = await BuildCollectionStrategyBaseData(data)
    if (res.success) {
      companyGradeList.value = res?.data.fieldInfoData.filter(item => item.dictName == 'CollectionDifficulty')[0].selectOptions
      retailGradeList.value = res?.data.fieldInfoData.filter(item => item.dictName == 'CollectionDifficulty')[0].selectOptions
      collectionTimeList.value = res?.data.fieldInfoData.filter(item => item.dictName == 'CollectionTime')[0]
      collectionTypeList.value = res?.data.fieldInfoData.filter(item => item.dictName == 'CollectionType')[0]
      precollectionList.value = res?.data.fieldInfoData.filter(item => item.dictName == '前期催收')[0].selectOptions
      territorialCollectionList.value = res?.data.fieldInfoData.filter(item => item.dictName == '属地催收')[0].selectOptions
      outsourcedCollectionList.value = res?.data.fieldInfoData.filter(item => item.dictName == '委外催收')[0].selectOptions
    } else {
      ElMessage.error(res.msg);
    }
  }
  function addLevel() {
    if (companyList.length == 5) {
      ElMessage.warning('最多只能创建五个催收难度策略')
      return
    }
    companyList.push({
      evaluationGrade: '',
      collectionType: '',
      collectionMethod: '',
      minOverdueAmount: '',
      maxOverdueAmount: '',
      collectionTime: '',
      collectionByList: [],
    })
  }


  function deleteCompany() {
    if (companyList.length == 1) {
      ElMessage.warning('至少保留一个催收难度策略')
    } else {
      companyList.pop()
    }
  }
  function addLevel1() {
    if (retailList.length == 5) {
      ElMessage.warning('最多只能创建五个催收难度策略')
      return
    }
    retailList.push({
      evaluationGrade: '',
      collectionType: '',
      collectionMethod: '',
      minOverdueAmount: '',
      maxOverdueAmount: '',
      collectionTime: '',
      collectionByList: [],
    })
  }

  function deleteRetail() {
    if (retailList.length == 1) {
      ElMessage.warning('至少保留一个催收难度策略')
    } else {
      retailList.pop()
    }
  }

  async function ShowReportDestail(row) {
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      detailId: row.collectionStrategyModelId
    }
    let res = await CollectionStrategyDetail(data)
    if (res.success) {
      showType.value = res?.data.customerType
      showTitle.value = res?.data.policyName
      showData.value = res?.data.riskSignals
      detailVisible.value = true
    } else {
      ElMessage.error(res.msg);
    }
  }

  function CloseDetail() {
    detailVisible.value = false
  }

  onMounted(async () => {
    handleCreatedModelData()
    getList()
  })


  async function openNew() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      module: 2
    }
    let res = await IsLooked(data)
    if (res.data) {
      CreditVisible.value = true;
    } else {
      ElMessage.warning('请先识别逾期客户')
    }
  }
  return {
    dataList,
    loading,
    CreditVisible,
    pagination,
    columns,
    formData,
    handleCurrentChange,
    handleSizeChange,
    SubmitVisible,
    companyGradeList,  //公司客户等级
    retailGradeList,  //零售客户等级
    collectionTimeList, //催收时间
    collectionTypeList, //催收类型
    //根据类型联动
    precollectionList,
    territorialCollectionList,
    outsourcedCollectionList,
    retailList,
    companyList,
    BtnLoading,
    updateTypeSelect,
    addLevel,
    updateTypeSelect1,
    addLevel1,
    CloseVisible,
    ShowReportDestail,
    CloseDetail,
    detailVisible,
    showData,
    showTitle,
    showType,
    deleteCompany,
    deleteRetail,
    openNew
  }
}
